from PySide6.QtWidgets import QApplication,QWidget,QPushButton,QMessageBox
from PySide6.QtCore import QThread,QThreadPool,QRect,QFile,QTextStream
from PySide6.QtCore import QFile, QJsonDocument
from .application_ui import Ui_Form


def read_json_file(file_path):
    # 创建 QFile 对象
    file = QFile(file_path)
    
    # 打开文件
    if not file.open(QFile.ReadOnly | QFile.Text):
        print(f"无法打开文件 {file_path}")
        return None
    
    # 读取文件内容
    data = file.readAll()
    file.close()
    
    # 解析 JSON 数据
    json_doc = QJsonDocument.fromJson(data)
    if json_doc.isNull():
        print("无效的 JSON 格式")
        return None
    
    # 获取 JSON 对象
    json_object = json_doc.object()
    return json_object




class MyWidget(QWidget):
    def __init__(self):
        super().__init__()
        self.ui = Ui_Form()
        self.ui.setupUi(self)
        self.SetVar()
        self.SetUi()
        self.SetBind()
        self.SetHook()
        self.SetThread()
        self.SetQThreadPool()

    def SetVar(self):
        self.threadObject = QThread()        
        self.ThreadPool = QThreadPool()
        self.ThreadPool.setMaxThreadCount(10)


    def SetUi(self):
        self.setWindowTitle("窗口标题!")
        self.setGeometry(QRect(50,50,800,500))
        self.CreateUi()

    def SetBind(self):
        pass

    def SetHook(self):
        pass

    def SetThread(self):
        pass

    def SetQThreadPool(self):
        pass


    def closeEvent(self, event) -> None:
        # 重写了这个主窗口的关闭程序.这样子在主线程关闭的时候,也会关闭子线程.
        # 停止线程
        # 终止线程池中的所有线程
        self.threadObject.quit()
        self.threadObject.wait()
        self.ThreadPool.clear()
        print("主线程关闭")
        event.accept()

    def CreateUi(self):
        self.CreateButton()
    
    def CreateButton(self):
        command = lambda event : [print("hello"),
                                  print("world"),
                                  work := "使用海象表达式创建!",  # 在 lambda 表达式中创建变量的话,需要使用 海象表达式
                                  print(work)]
        self.button = QPushButton("按钮",self)
        self.button.resize(100, 80)
        self.button.move(100, 50)
        self.button.clicked.connect(command)
        self.button.setStyleSheet("QPushButton{background-color: lightgray;border: 2px solid gray;border-radius: 5px;padding: 5px 10px;}QPushButton:hover {background-color: lightblue;border: 2px solid blue;}")
        
        